import { createElement, Component } from './framwork';

export class Carousel extends Component {
  constructor() {
    super()
    this.attributes = {}
  }
  render() {
    this.root = document.createElement('div')
    this.root.classList.add('carousel')
    for (let url of this.attributes.src) {
      const dom = document.createElement('div')
      dom.style.backgroundImage = `url(${url})`
      this.root.appendChild(dom)
    }

    let position = 0
    this.root.addEventListener('mousedown', event => {
      const children = this.root.children
      const startX = event.clientX

      const move = event => {
        const x = event.clientX - startX

        const current = position - ((x - x % 500) / 500)

        for (let offset of [-1, 0, 1]) {
          let pos = current + offset
          // 取余小技巧-2 -> 2, -3 -> 3
          pos = (pos + children.length) % children.length
          children[pos].style.transition = 'none'
          children[pos].style.transform = `translateX(${-pos * 500 + offset * 500 + x % 500}px)`
        }
      }
      const up = event => {
        const x = event.clientX - startX
        position -= Math.round(x / 500)
        for (let offset of [0, -Math.sign(Math.round(x / 500) - x + 250 * Math.sign(x))]) {
          let pos = position + offset
          // 取余小技巧-2 -> 2, -3 -> 3
          pos = (pos + children.length) % children.length
          children[pos].style.transition = ''
          children[pos].style.transform = `translateX(${-pos * 500 + offset * 500}px)`
        }
        document.removeEventListener('mousemove', move)
        document.removeEventListener('mouseup', up)
      }

      document.addEventListener('mousemove', move)
      document.addEventListener('mouseup', up)
    })

    /* let currentIndex = 0
    setInterval(() => {
      const children = this.root.children
      const nextIndex = (currentIndex + 1) % children.length

      const current = children[currentIndex]
      const next = children[nextIndex]

      next.style.transition = `none`
      next.style.transform = `translateX(${100 - nextIndex * 100}%)`

      setTimeout(() => {
        next.style.transition = ``
        current.style.transform = `translateX(${-100 - currentIndex * 100}%)`
        next.style.transform = `translateX(${-nextIndex * 100}%)`
        currentIndex = nextIndex
      }, 16);
    }, 3000); */
    return this.root
  }
  setAttribute(name, value) {
    this.attributes[name] = value
  }
  mountTo(parent) {
    parent.appendChild(this.render())
  }
}